//
//  GZTabScrollView.m
//  GZGroup
//
//  Created by guozhengmao on 15/9/17.
//  Copyright (c) 2015年 guozhengmao. All rights reserved.
//

#import "GZTabScrollView.h"
#import "ImageManager.h"
@implementation GZTabScrollView
-(id)init{
    self=[super init];
    if (self) {
        [self setDefualtNums];
    }
    return self;
}
-(id)initWithCoder:(NSCoder *)aDecoder{
    self=[super initWithCoder:aDecoder];
    if (self) {
        [self setDefualtNums];
    }
    return self;
}
-(id)initWithFrame:(CGRect)frame{
    self=[super initWithFrame:frame];
    if (self) {
        [self setDefualtNums];
    }
    return self;
}
//创建视图的方法
-(void)buildWithTitleArray:(NSArray*)titleArray withSubViewArray:(NSArray*)subViewArray{
    //无法创建视图
    if ([titleArray count]==0||[titleArray count]!=[subViewArray count]) {
        return;
    }
    _subViewArray=nil;
    _subViewArray=[NSMutableArray arrayWithArray:subViewArray];
    [self buildBaseNums];
    __block BOOL error=NO;
    NSMutableArray *viewArray=[[NSMutableArray alloc] initWithCapacity:_pageCount];
    [titleArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        if ([[obj class] isSubclassOfClass:[NSString class]]) {
            UILabel *lb=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, _cellWidth, _tabBarHeight)];
            [lb setText:obj];
            [lb setTextColor:[UIColor whiteColor]];
            lb.textAlignment=NSTextAlignmentCenter;
            [viewArray addObject:lb];
        }else{
            error=YES;
            *stop=YES;
        }
        
    }];
    //出现异常退出
    if (error) {
        return;
    }
    [self buildWithViewArray:viewArray];
    
}
-(void)buildWithImageArray:(NSArray*)imgArray withSubViewArray:(NSArray*)subViewArray{
    //无法创建视图
    if ([imgArray count]==0||[imgArray count]!=[subViewArray count]) {
        return;
    }
    _subViewArray=nil;
    _subViewArray=[NSMutableArray arrayWithArray:subViewArray];
    [self buildBaseNums];
    __block BOOL error=NO;
    NSMutableArray *viewArray=[[NSMutableArray alloc] initWithCapacity:_pageCount];
    [imgArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        if ([[obj class] isSubclassOfClass:[UIImage class]]) {
            UIImage *img=(UIImage*)obj;
            CGRect f=[ImageManager getFrameWithImageSize:img.size withContentSize:CGSizeMake(_cellWidth, _tabBarHeight)];
            UIImageView *imgView=[[UIImageView alloc] initWithFrame:f];
            [imgView setImage:img];
            [viewArray addObject:imgView];
        }else{
            error=YES;
            *stop=YES;
        }
        
    }];
    //出现异常退出
    if (error) {
        return;
    }

     [self buildWithViewArray:viewArray];
}
-(void)buildWithViewArray:(NSArray*)viewArray withSubViewArray:(NSArray*)subViewArray{
    //无法创建视图
    if ([subViewArray count]==0||[viewArray count]!=[subViewArray count]) {
        return;
    }
    _subViewArray=nil;
    _subViewArray=[NSMutableArray arrayWithArray:subViewArray];
    [self buildBaseNums];
    [self buildWithViewArray:viewArray];
}
-(void)buildWithViewArray:(NSArray *)viewArray{
    [self buildTabBarWithArray:viewArray];
    [self buildCusorView];
    [self buildScrollView];
    [self buildPageControl];
    [self showPageWithPageIndex:0];
}
-(void)buildTabBarWithArray:(NSArray*)viewArray{
    if (_tabBarView==nil) {
        _tabBarView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, _with, _tabBarHeight)];
        _tabBarItemArray=[[NSMutableArray alloc] initWithCapacity:_pageCount];
        [self addSubview:_tabBarView];
        
    }
    //根据类型选择所放置的位置
    if (_tabBarType==0) {
        _tabBarView.frame=CGRectMake(0, 0, _with, _tabBarHeight);
    }else{
        _tabBarView.frame=CGRectMake(0, self.frame.size.height-_tabBarHeight, _with,_tabBarHeight);
    }
    //清楚原本的tabBarItem
    [_tabBarItemArray enumerateObjectsUsingBlock:^(UIView* subView, NSUInteger idx, BOOL *stop) {
        [subView removeFromSuperview];
    }];
    [_tabBarItemArray removeAllObjects];
    //加载新的tabBarItem
    [viewArray enumerateObjectsUsingBlock:^(UIView* subView, NSUInteger idx, BOOL *stop) {
        UIView *tabItem=[[UIView alloc] initWithFrame:CGRectMake(_cellWidth*idx, 0, _cellWidth, _tabBarHeight)];
        [tabItem setBackgroundColor:_tabItemNormalColor];
        tabItem.tag=idx;
        [tabItem addSubview:subView];
        UIButton *bt=[UIButton buttonWithType:UIButtonTypeCustom];
        bt.frame=CGRectMake(0, 0, _cellWidth, _tabBarHeight);
        [tabItem addSubview:bt];
        bt.tag=idx;
        [bt addTarget:self action:@selector(tapAction:) forControlEvents:UIControlEventTouchUpInside];
        [_tabBarItemArray addObject:tabItem];
        [_tabBarView addSubview:tabItem];
    }];
}
-(void)buildCusorView{
    if (_cusorLineView==nil) {
        _cusorLineView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, _with, 0.5)];
        
        _cusorView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, _cellWidth, 2)];
       
        [_tabBarView addSubview:_cusorLineView];
        [_cusorLineView addSubview:_cusorView];
    }
    if (_cusorType==0) {
        _cusorLineView.frame=CGRectMake(0, 0, _with, 0.5);
    }else{
        _cusorLineView.frame=CGRectMake(0, _tabBarHeight-1, _with, 0.5);
    }
    _cusorView.frame=CGRectMake(0, 0, _cellWidth, 2);
    [_cusorLineView setBackgroundColor:_cusorLineColor];
    [_cusorView setBackgroundColor:_cusorColor];
}
-(void)buildScrollView{
    if (_scrollView==nil) {
        _scrollView=[[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
        _scrollView.pagingEnabled=YES;
        _scrollView.showsHorizontalScrollIndicator=NO;
        _scrollView.showsVerticalScrollIndicator=NO;
        _scrollView.bounces=NO;
        _scrollView.delegate=self;
        [self addSubview:_scrollView];
    }
    if (_tabBarType==0) {
        _scrollView.frame=CGRectMake(0, _tabBarHeight, _with, self.frame.size.height-_tabBarHeight);
    }else{
        _scrollView.frame=CGRectMake(0, 0, _with, self.frame.size.height-_tabBarHeight);
    }
    [_scrollView.subviews enumerateObjectsUsingBlock:^(UIView *  obj, NSUInteger idx, BOOL *  stop) {
        [obj removeFromSuperview];
    }];
    [_scrollView setContentOffset:CGPointMake(0, 0)];
    [_scrollView setContentSize:CGSizeMake(_with*_pageCount, _scrollView.frame.size.height)];
    [_subViewArray enumerateObjectsUsingBlock:^(UIView* obj, NSUInteger idx, BOOL *  stop) {
//在多屏幕尺寸下有点麻烦 暂时的解决方案是居中显示视图 最直接，简单粗暴省时间
//        UIView *view=[[UIView alloc] initWithFrame:CGRectMake(_with*idx, 0, _with, self.frame.size.height-_tabBarHeight)];
//        [_scrollView addSubview:view];
//        view.clipsToBounds=YES;
//        [view addSubview:obj];
//        [_scrollView addSubview:obj];
//        obj.center=view.center;
        
        //多尺寸下 第二套解决方案，直接改变视图尺寸，他自己的内容自己去适配 当视图大小发生变化的时候自己去调整
        //应该死是使用kvo之类的
        //也可以是子视图直接使用autolayout这样子视图就会发生变化了，感觉这样比较合理
        obj.frame=CGRectMake(_with*idx, 5, _with, _scrollView.frame.size.height-5);
        obj.clipsToBounds=YES;
        [_scrollView addSubview:obj];
    }];
    
}
-(void)buildPageControl{
    if (_pageControl==nil) {
        _pageControl=[[UIPageControl alloc] init];
        [self addSubview:_pageControl];
        _pageControl.userInteractionEnabled=NO;
    }
    _pageControl.numberOfPages=_pageCount;
    CGSize size=[_pageControl sizeForNumberOfPages:_pageCount];
    _pageControl.bounds=CGRectMake(0, 0, size.width, size.height);
    _pageControl.center=CGPointMake(self.frame.size.width *0.5,_pageControlY);
    _pageControl.currentPageIndicatorTintColor=[UIColor whiteColor];
    _pageControl.pageIndicatorTintColor=[UIColor grayColor];
}
//根据当前状态设置基础数值
-(void)buildBaseNums{
    _with=self.frame.size.width;
    _pageCount=[_subViewArray count];
    _cellWidth=_with/_pageCount;
    _pageIndex=0;
}
//设置默认值
-(void)setDefualtNums{
    _pageIndex=0;
    _tabBarType=0;
    _cusorType=0;
    _tabBarHeight=40;
    _pageControlY=-1;
    _tabItemNormalColor=[UIColor grayColor];
    _tabItemSelectedColor=[UIColor blackColor];
    _cusorColor=[UIColor redColor];
    _cusorLineColor=[UIColor grayColor];
}
-(void)scrollToPage:(NSInteger)pageIndex{
    [self showPageWithPageIndex:pageIndex];
}
#pragma mark 次级方法
/*
 事件，次级方法
 */
-(void)showPageWithTabItem:(UIView*)item{
    [self showPageWithPageIndex:item.tag];
}
//显示特定页数
//这里应当有一个事件，尝试用block来代替delegate
-(void)showPageWithPageIndex:(NSInteger)index{
    if (index<0||index>_pageCount) {
        return;
    }
    UIView *selectedTabBarItem=[_tabBarItemArray objectAtIndex:index];
    if (selectedTabBarItem==_selectedTabBarItem) {
        //selectCancelBlock事件
        return;
    }
    //shouldSelectTabBarItemBlock if yes go on
    _pageIndex=index;
    [_selectedTabBarItem setBackgroundColor:_tabItemNormalColor];
    _selectedTabBarItem=selectedTabBarItem;
    [_selectedTabBarItem setBackgroundColor:_tabItemSelectedColor];
    _pageControl.currentPage=_pageIndex;
    [_scrollView setContentOffset:CGPointMake(_with*_pageIndex, 0) animated:YES];
    if (self.didSelectTabBarItemBlock!=nil) _didSelectTabBarItemBlock(self,_pageIndex);
    //didSelectTabBarItemBlock
    //如果是lable view 还可以在这里讲Lable传递给用户，叫用户修改属性
}
//响应tab点击事件
-(void)tapAction:(UIButton*)sender{
    [self showPageWithPageIndex:sender.tag];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/
//设置属性方法
#pragma mark 设置属性方法

-(CGSize)getSubViewSize{
    return CGSizeMake(self.frame.size.width, self.frame.size.height-_tabBarHeight);
}
-(CGSize)getTabBarItemSizeWithPageCount:(NSInteger)pageCount{
    return CGSizeMake(self.frame.size.width/pageCount, _tabBarHeight);
}
-(void)setPageControlLightColor:(UIColor*)color{
    _pageControl.currentPageIndicatorTintColor=color;
}
-(void)setCusorType:(int)type{
    _cusorType=type;
}
-(void)setTabItemNormalColor:(UIColor*)color{
    _tabItemNormalColor=color;
}
-(void)setTabItemSelectedColor:(UIColor*)color{
    _tabItemSelectedColor=color;
}
-(void)setTabBarHeight:(int)height{
    _tabBarHeight=height;
}
-(void)setPageControlY:(int)y{
    _pageControlY=y;
}
-(void)setCusorColor:(UIColor*)cusorColor withCusorLineColor:(UIColor*)lineColor{
    _cusorLineColor=lineColor;
    [_cusorLineView setBackgroundColor:_cusorLineColor];
    _cusorColor=cusorColor;
    [_cusorView setBackgroundColor:_cusorColor];
}
-(void)addPageControl{
    [self addSubview:_pageControl];
}
-(void)removePageControl{
    [_pageControl removeFromSuperview];
}
-(void)addButtons{
    if (_leftBT==nil) {
        _leftBT=[UIButton buttonWithType:UIButtonTypeCustom];
        _rightBT=[UIButton buttonWithType:UIButtonTypeCustom];
        [_leftBT setImage:[UIImage imageNamed:@"left_01.png"] forState:UIControlStateNormal];
        [_rightBT setImage:[UIImage imageNamed:@"right_01.png"] forState:UIControlStateNormal];
        [self addSubview:_leftBT];
        [self addSubview:_rightBT];
        [_leftBT addTarget:self action:@selector(leftBTAction) forControlEvents:UIControlEventTouchUpInside];
        [_rightBT addTarget:self action:@selector(rightBTAction) forControlEvents:UIControlEventTouchUpInside];
    }
    _leftBT.bounds=CGRectMake(0, 0, 18, 36);
    _leftBT.center=CGPointMake(42, self.frame.size.height*0.5+10);
    _rightBT.bounds=CGRectMake(0, 0, 18, 36);
    _rightBT.center=CGPointMake(self.frame.size.width-42, self.frame.size.height*0.5+10);
}
-(void)leftBTAction{
    NSInteger pageIndex=_pageIndex-1;
    if (pageIndex<0) {
        return;
    }
    [self showPageWithPageIndex:pageIndex];
}
-(void)rightBTAction{
    NSInteger pageIndex=_pageIndex+1;
    if (pageIndex>=_pageCount) {
        return;
    }
    [self showPageWithPageIndex:pageIndex];
}
-(void)removeButtons{
    [_leftBT removeFromSuperview];
    _leftBT=nil;
    [_rightBT removeFromSuperview];
    _rightBT=nil;
}

#pragma mark 委托事件方法
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    _userTouchScrollView=YES;
}
//手指滑动scrollView结束
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    int xx=(int)scrollView.contentOffset.x%_with;
    if(xx==0){
        int pageIndex=scrollView.contentOffset.x/_with;
        [self showPageWithPageIndex:pageIndex];
    }
    _userTouchScrollView=NO;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (!_userTouchScrollView) {
      //auto scroll
    }else{
      //user scroll
    }
    _cusorView.frame=CGRectMake(scrollView.contentOffset.x/_pageCount, 0, _cellWidth, 2);
}
@end
